﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using ZH.Infrastructure.Dto.Request.Login;
using ZH.Infrastructure.Dto.Response.admin;
using ZH.Infrastructure.Dto.Response;
using ZH.Infrastructure.Tools;
using ZH.Service.Interface;
using ZH.Service.Instance;
using ServiceStack.Text;
using Microsoft.Extensions.Caching.Memory;
using Config = ZH.Infrastructure.Tools.Config;
using NETCore.MailKit.Core;
using Microsoft.AspNetCore.Identity.Data;

namespace ZH.Api.Admin.Controllers.Mobile
{
    /// <summary>
    /// 移动端·用户登录
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]

    public class MobileController : Controller
    {
        public readonly I_Mobile_Service _mobile_Service;
        public readonly I_Yuyue_Service _i_yuyue_Service;
        public readonly IConfiguration _configuration;
        private readonly I_Email_Service _emailService;
        private readonly IMemoryCache _cache;

        public MobileController(
            I_Mobile_Service mobile_Service,
            IConfiguration configuration,
            I_Yuyue_Service i_Yuyue_Service,
            I_Email_Service emailService,
            IMemoryCache cache
            ) {
            _mobile_Service = mobile_Service;
            _i_yuyue_Service = i_Yuyue_Service;
            _configuration = configuration;
            _emailService = emailService;
            _cache = cache;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Logins(Login_Request_Dto dto)
        {
            dto.code = Config.GUID2();
            var result = await _mobile_Service.Logins(dto);
            if (result.code == Api_Code.ok)
            {

                var claims = new[]
                 {
                    new Claim(ClaimTypes.Name,  dto.code),
                    new Claim(ClaimTypes.Actor,dto.account!.Trim()),
                    new Claim(ClaimTypes.Role,"Mobile")
                };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecurityKey"]));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                string jwtKey = _configuration["JWT:issuer"];
                var token = new JwtSecurityToken(
                    issuer: jwtKey,
                    audience: jwtKey,
                    claims: claims,
                    expires: DateTime.Now.AddMinutes(60 * 60 * 12),
                    signingCredentials: creds);

                result.data = new
                {
                    token = new JwtSecurityTokenHandler().WriteToken(token)
                };
            }
            //
            return Ok(result);
        }



        /// <summary>
        /// 请输入邮箱进行验证
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        [HttpPost("SendVerificationCode/{email}")]
        public async Task<IActionResult> SendVerificationCode(string email) {


            if (string.IsNullOrEmpty(email))
            {
                return BadRequest("邮箱不能为空");
            }

            try
            {
                var code = await _emailService.SendVerificationCodeAsync(email);

                // 将验证码存入缓存，设置5分钟过期
                _cache.Set($"VerificationCode:{email}", code, TimeSpan.FromMinutes(5));
                return Ok("验证码已发送，请查收");
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

        }
        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        // 第二步：验证验证码并完成登录
        [HttpPost("login-with-email")]
        public IActionResult LoginWithEmail([FromBody] LoginRequest request)
        {
            if (!_cache.TryGetValue($"VerificationCode:{request.Email}", out string storedCode))
            {
                return BadRequest("验证码已过期或未发送，请重新获取");
            }

            if (storedCode != request.VerificationCode)
            {
                return BadRequest("验证码不正确");
            }
            // 验证码验证成功，执行注册逻辑（生成Token等）

            var result = _mobile_Service.Register(
                request.Email, request.password,request.phone

                );


            // 清除已使用的验证码
            _cache.Remove($"VerificationCode:{request.Email}");

            return Ok(result);
        }

        public class LoginRequest
        {
            public string Email { get; set; }
            public string VerificationCode { get; set; }
            public string password {  get; set; }
            public string phone {  get; set; }
        }

        /// <summary>
        /// 检查登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Roles = "Mobile")] 
        public IActionResult Check_Login()  
        {

            var user = this.Get_Current_Mobile();
            if (user == null)
            {
                return Unauthorized();//返回401
            }

            return Ok(new Api_Response_Dto
            {

                code = 0,
                message = "ok",
                data = user
            });
        }

        /// <summary>
        /// 获取当前登录的客户
        /// </summary>
        /// <returns></returns>
        private User_Response_Dto? Get_Current_Mobile()
        {
            var code = Response.HttpContext.User.Identity?.Name;

            return _mobile_Service.Check_Login(code, "");
        }
  
    }
}
